<?php

/**
 * 房源推送信息处理
 */

namespace push;


use app\api\model\UserDemand;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use custom\Redis;
use think\Exception;

class House {

    /**
     * 需要推送的用户
     * @var string
     */
    protected static $pushUser = RedisKey::PUSH_HOUSE_USERS;

    /**
     * 用户需要推送的房源
     * @var string
     */
    protected static $pushUserHouse = RedisKey::PUSH_USER_HOUSES;

    /**
     * 推送的新增房源集合
     * @var string
     */
    protected static $houseRedisKey = RedisKey::PUSH_ADD_HOUSE;

    /**
     * 数据统计
     * @param $params
     * @param $type
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function statistics($params, $type) {
        switch ($type) {
            // 房源数据统计
            case "house":
                static::statisticsHouse($params);
                break;
            // 小区绑定数据统计
            case "village":
                static::statisticsVillage($params);
                break;
            default:
                break;
        }
    }

    /**
     * 房源信息统计,限小区或者区域
     * @param $village
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function statisticsVillage($village) {

        // 获取新增的房源集合
        $redis = Redis::getInstance();
        $houseIds = $redis->smembers(static::$houseRedisKey);

        // 不属于新增，直接返回true
        if(!in_array($village['house_id'], $houseIds)) {
            return true;
        }

        // 获取小区信息
        if(!$villageData = db('house_village')->where(['id' => $village['village_id']])->find()) {
            throw new Exception('不存在该小区', RespCode::PARAMS_ERR);
        }

        // 获取房源信息
        $house = Db::name('house')->alias('h')
            ->join('house_auction ha', 'h.auction_id = ha.id', 'LEFT')
            ->field('h.id as house_id,h.build_area,ha.initial_price,h.city_code')
            ->where(['ha.source_id' => $village['house_id']])
            ->find();

        // 获取定制需求：只看小区
        $where = [
            ['type', '=', UserDemand::TYPE2],
            ['area_code', '=', $house['city_code']],
            ['type_id', '=', $villageData['id']],
        ];
        $vDdemand = db('UserDemand')->where($where)->select();

        // 获取定制需求：只看商圈
        $where = [
            ['type', '=', UserDemand::TYPE3],
            ['area_code', '=', $house['city_code']],
            ['type_id', '=', $villageData['business_area']],
        ];
        $bDdemand = db('UserDemand')->where($where)->select();

        // 区间筛选及统计数据
        static::screenData(array_merge($vDdemand, $bDdemand), $house);
    }

    /**
     * 房源信息统计,不限小区或者区域
     * @param $house
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private static function statisticsHouse($house) {
        // 不是待开始，不统计数据
        if($house['auction_status'] != 1) {
            return true;
        }

        // 新增房源来源id
        $redis = Redis::getInstance();
        $redis->sadd(static::$houseRedisKey, $house['source_id']);

        // 不限类型、并满足区域
        $where = [
            ['type', '=', UserDemand::TYPE1],
            ['area_code', '=', $house['city_code']],
        ];

        // 获取不限类型的定制需求
        $demand = db('UserDemand')->where($where)->select();
        // 区间筛选及统计数据
        static::screenData($demand, $house);
    }

    /**
     * 区间筛选及统计数据
     * @param $demand
     * @param $house
     */
    private static function screenData($demand, $house) {
        $person = [];
        foreach ($demand as $val) {

            // 价格区间
            if (!is_section($house['initial_price'], $val['price_section'])) {
                break;
            }

            // 面积区间
            if (!is_section($house['build_area'], $val['area_section'])) {
                break;
            }

            // 统计单个用户房源个数
            if (!isset($person[ $val['user_id'] ])) {
                static::redisHandle($house['house_id'], $val['user_id']);
                $person[ $val['user_id'] ] = 1;
            }
        }
    }

    /**
     * redis数据处理
     * @param $houseId 房源id
     * @param $userId 用户id
     */
    public static function redisHandle($houseId, $userId) {
        $redis = Redis::getInstance();
        // 需要推送的用户
        $redis->sadd(static::$pushUser, $userId);
        $redisKey = static::$pushUserHouse . $userId;
        // 用户需要推送的房源
        $redis->sadd($redisKey, $houseId);
    }

}